package org.dromara.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import org.dromara.business.domain.User;
import org.dromara.business.service.BusinessConfigService;
import org.dromara.business.service.UserService;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.utils.MapstructUtils;
import cn.hutool.core.util.StrUtil;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.websocket.utils.WebSocketUtils;
import org.springframework.stereotype.Service;
import org.dromara.business.domain.bo.BusinessInformationBo;
import org.dromara.business.domain.vo.BusinessInformationVo;
import org.dromara.business.domain.BusinessInformation;
import org.dromara.business.mapper.BusinessInformationMapper;
import org.dromara.business.service.BusinessInformationService;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 信息Service业务层处理
 *
 * @author zlj
 * @date 2024-11-18
 */
@RequiredArgsConstructor
@Service
public class BusinessInformationServiceImpl extends ServiceImpl<BusinessInformationMapper,BusinessInformation> implements BusinessInformationService {

    private final BusinessInformationMapper baseMapper;
    private final UserService userService;
    private final ScheduledExecutorService scheduledExecutorService;

    /**
     * 查询信息
     */
    @Override
    public BusinessInformationVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询信息列表
     */
    @Override
    public TableDataInfo<BusinessInformationVo> queryPageList(BusinessInformationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BusinessInformation> lqw = buildQueryWrapper(bo);
        Page<BusinessInformationVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (BusinessInformationVo record : result.getRecords()) {
            record.setDz(record.getProvince()+record.getCity()+record.getDistance());
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询信息列表
     */
    @Override
    public List<BusinessInformationVo> queryList(BusinessInformationBo bo) {
        LambdaQueryWrapper<BusinessInformation> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BusinessInformation> buildQueryWrapper(BusinessInformationBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BusinessInformation> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getFlId() != null, BusinessInformation::getFlId, bo.getFlId());
        lqw.eq(StrUtil.isNotBlank(bo.getBt()), BusinessInformation::getBt, bo.getBt());
        lqw.like(StrUtil.isNotBlank(bo.getNr()), BusinessInformation::getNr, bo.getNr());
        lqw.eq(StrUtil.isNotBlank(bo.getPhoto()), BusinessInformation::getPhoto, bo.getPhoto());
        lqw.eq(StrUtil.isNotBlank(bo.getDz()), BusinessInformation::getDz, bo.getDz());
        lqw.eq(StrUtil.isNotBlank(bo.getSf()), BusinessInformation::getSf, bo.getSf());
        lqw.like(StrUtil.isNotBlank(bo.getLxrXm()), BusinessInformation::getLxrXm, bo.getLxrXm());
        lqw.eq(StrUtil.isNotBlank(bo.getLxrDh()), BusinessInformation::getLxrDh, bo.getLxrDh());
        lqw.eq(StrUtil.isNotBlank(bo.getShzt()), BusinessInformation::getShzt, bo.getShzt());
        lqw.eq(StrUtil.isNotBlank(bo.getShly()), BusinessInformation::getShly, bo.getShly());
        lqw.like(StrUtil.isNotBlank(bo.getCity()), BusinessInformation::getCity, bo.getCity());
        lqw.eq(StrUtil.isNotBlank(bo.getLxNameYj()), BusinessInformation::getLxNameYj, bo.getLxNameYj());
        lqw.eq(StrUtil.isNotBlank(bo.getLxNameEj()), BusinessInformation::getLxNameEj, bo.getLxNameEj());
        lqw.eq(bo.getUserId() != null, BusinessInformation::getUserId, bo.getUserId());
        lqw.orderByDesc(BusinessInformation::getCreateTime);
        return lqw;
    }

    /**
     * 新增信息
     */
    @Override
    public Boolean insertByBo(BusinessInformationBo bo) {
        BusinessInformation add = MapstructUtils.convert(bo, BusinessInformation.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }

        scheduledExecutorService.schedule(() -> {
            WebSocketUtils.sendMessage(UserConstants.SUPER_ADMIN_ID, "用户+"+bo.getCreateBy()+"发布了信息");
        }, 0, TimeUnit.SECONDS);
        return flag;
    }





































    /**
     * 修改信息
     */
    @Override
    public Boolean updateByBo(BusinessInformationBo bo) {
        BusinessInformation update = MapstructUtils.convert(bo, BusinessInformation.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusinessInformation entity){
        BusinessInformationVo businessInformationVo = baseMapper.selectVoById(entity.getId());

        if (ObjectUtil.isNotNull(businessInformationVo)&&
            !entity.getShzt().equals(businessInformationVo.getShzt())  ){

            entity.setApprovalTime(new Date());
            if  ("2".equals(entity.getShzt())  ){
                BusinessInformation business = this.getById(entity.getId());
                int date=3;
                if ("1".equals(business.getVip())){
                    date=7;
                }else if ("2".equals(business.getVip())){
                    date=30;
                }else if ("3".equals(business.getVip())){
                    date=365;
                }
                // 计算当前时间加上指定天数后的时间
                LocalDateTime currentTime = LocalDateTime.now();
                LocalDateTime newTime = currentTime.plusDays(date);
                Date gqTime = Date.from(newTime.atZone(ZoneId.systemDefault()).toInstant());
                entity.setExpirationDate(gqTime);
            }
        }

    }

    /**
     * 批量删除信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean refresh(Long id,String type) {
//        获取当前用户id
        Long userId = LoginHelper.getUserId();
        User user = userService.getById(userId);
        boolean update=false;
        if ("1".equals(type)){
            if (null ==user.getRedeemNumer()){
                user.setRedeemNumer(0);
            }
            if (user.getRedeemNumer()<=0){
                throw new IllegalArgumentException("积分兑换置顶次数已用完");
            }

            user.setRedeemNumer(user.getRedeemNumer()-1);
            userService.updateById(user);
            Date date = new Date();
            update = this.lambdaUpdate()
                .set(BusinessInformation::getUpdateTime, date)
                .set(BusinessInformation::getCreateTime, date)
                .eq(BusinessInformation::getId, id).update();
        }else{

            if (user.getRefreshTimes()<=0){
                throw new IllegalArgumentException("会员置顶次数已用完");
            }
            user.setRefreshTimes(user.getRefreshTimes()-1);
            userService.updateById(user);
            Date date = new Date();
             update = this.lambdaUpdate()
                .set(BusinessInformation::getUpdateTime, date)
                .set(BusinessInformation::getCreateTime, date)
                .eq(BusinessInformation::getId, id).update();

        }





        return update;
    }

    /**
     * 审核
     * @param bo
     * @return
     */
    @Override
    public Boolean reviewAdvertisements(BusinessInformationBo bo) {
        BusinessInformation update = MapstructUtils.convert(bo, BusinessInformation.class);
        if  ("2".equals(update.getShzt())  ){
            BusinessInformation business = this.getById(bo.getId());
            int date=3;
            if ("1".equals(business.getVip())){
                date=7;
            }else if ("2".equals(business.getVip())){
                date=30;
            }else if ("3".equals(business.getVip())){
                date=365;
            }
            // 计算当前时间加上指定天数后的时间
            LocalDateTime currentTime = LocalDateTime.now();
            LocalDateTime newTime = currentTime.plusDays(date);
            Date gqTime = Date.from(newTime.atZone(ZoneId.systemDefault()).toInstant());
            update.setExpirationDate(gqTime);
        }
        update.setUpdateTime(new Date());
        update.setUpdateBy(LoginHelper.getUserId());
        return baseMapper.updateById(update) > 0;
    }
}
